package com.atguigu.tingshu.album.taxk;

import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.model.album.AlbumInfo;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/***
 * 专辑可靠性投递同步数据
 */
@Component
public class AlbumMessagefailTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    AlbumInfoService albumInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 定时任务同步失败住哪及数据
     * cron 秒分时日月周
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void albumMessageFailTask(){
        //从redis中获取所有失误的专辑id信息
        Set<String> albumIdSet= redisTemplate.opsForSet().members("album_up_or_down");
        //遍历处理
        albumIdSet.stream().forEach(albumId->{
            try {
                //查询专辑数据
                AlbumInfo albumInfo = albumInfoService.getById(albumId);
                //判断是否公开
                CorrelationData correlationData = new CorrelationData();

                if (albumInfo.getIsOpen().equals("1")) {
                    correlationData.setReturned(new ReturnedMessage(new Message(albumId.toString().getBytes()), -1, null, null, "album.es.upper"));

                    //通知es
                    //上架
                    rabbitTemplate.convertAndSend("albuminfo_exchange", "album.es.upper", albumId + "",correlationData);

                } else {
                    correlationData.setReturned(new ReturnedMessage(new Message(albumId.toString().getBytes()), -1, null, null, "album.es.down"));
                    //下架
                    rabbitTemplate.convertAndSend("albuminfo_exchange", "album.es.down", albumId + "",correlationData);
                }
                //删除这个id
                redisTemplate.opsForSet().remove("album_up_or_down",albumId);
            } catch (AmqpException e) {
                e.printStackTrace();
            }
        });
    }
}
